package nl.justobjects.pushlet.wrapper;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.jms.Message;

import nl.justobjects.pushlet.core.Event;
import nl.justobjects.pushlet.pushmanager.PushManager;
import nl.justobjects.pushlet.pushmanager.PushManager.PushManageCommand;
import nl.justobjects.pushlet.util.Log;



public class PushletsListenner {

	@SuppressWarnings("unchecked")
	public void handleMessage(Message message) {
		try {
			String subject = (String) message.getObjectProperty("subject");
			String label = (String) message.getObjectProperty("label");
			List<String> pids = (List<String>) message.getObjectProperty("pids");
			
			Map<String, Serializable> data =  (Map<String, Serializable>) message.getObjectProperty("data");
			Map<String, Serializable> attributes = (Map<String, Serializable>) message.getObjectProperty("event");
			
			Event event = null;
			if (data == null && attributes != null) {
				event = new Event(attributes);
			}
			
			if (pids != null && pids.size() > 0) {
				for (String id : pids) {
					if (event != null) {
						PushManager.getInstance().unicastEvent(event, id);
					} else {
						PushManager.getInstance().unicastEvent(subject, label, data, id);
					}
				}
			} else {
				if (event != null) {
					PushManager.getInstance().multicastEvent(event);
				} else {
					PushManager.getInstance().multicastEvent(subject, label, data);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.error("[PushletsListenner]unexpected error:" + e.getMessage());
		}
	}
	
	public void handleMessage(Event event) {
		PushManager.getInstance().multicastEvent(event);
	}
	
	public void handleMessage(PushManageCommand command) {
		PushManager.getInstance().doCommand(command);
	}

}
